package cn.ichar.provide.mq;

import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @author imaye
 * @date 2021/8/19
 */
@Component
public class SpringProducer {
    private Logger logger = LoggerFactory.getLogger(SpringProducer.class);

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    //发送消息
    public void sendMessage(String msg, String topic) {
        rocketMQTemplate.convertAndSend(topic, msg);
    }

    //发送事务消息
    public void sendMessageIntransaction(String msg, String topic) {
        Message<String> message = MessageBuilder.withPayload(msg)
                .setHeader(RocketMQHeaders.TRANSACTION_ID, UUID.randomUUID().toString())
                .setHeader(RocketMQHeaders.TAGS, "group-lss")
                .setHeader("userid", "lss05555")
                .build();
        String destination = topic;
        TransactionSendResult sendResult = rocketMQTemplate.sendMessageInTransaction(destination, message, destination);
        logger.info("事务消息发送结果：", sendResult.toString());
    }
}
